
package com.dyzx.hbb.security.context;

import com.dyzx.hbb.security.model.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;

/**
 * 安全上下文持有者
 */
public class SecurityContextHolder {

    /**
     * 获取当前用户数据权限范围
     */
    public static String getDataScope() {
        LoginUser loginUser = getLoginUser();
        return loginUser != null ? loginUser.getDataScope() : null;
    }

    /**
     * 获取当前用户部门ID
     */
    public static Long getDeptId() {
        LoginUser loginUser = getLoginUser();
        return loginUser != null ? loginUser.getDeptId() : null;
    }
    public static Long getOrganId() {
        LoginUser loginUser = getLoginUser();
        return loginUser != null ? loginUser.getOrganId() : null;
    }

    public static boolean isAdmin() {
        LoginUser loginUser = getLoginUser();
        return loginUser != null && loginUser.isAdmin();
    }
    public static boolean isNotAdmin() {
        LoginUser loginUser = getLoginUser();
        if(loginUser == null){
            return true;
        }else {
            return !loginUser.isAdmin();
        }

    }
    /**
     * 获取当前登录用户
     */
    public static LoginUser getLoginUser() {
        SecurityContext context = org.springframework.security.core.context.SecurityContextHolder.getContext();
        if (context == null) {
            return null;
        }

        Authentication authentication = context.getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof LoginUser) {
            return (LoginUser) principal;
        }

        return null;
    }

    /**
     * 获取当前用户ID
     */
    public static Long getUserId() {
        LoginUser loginUser = getLoginUser();
        return loginUser != null ? loginUser.getId() : null;
    }

    /**
     * 获取当前用户名
     */
    public static String getUsername() {
        LoginUser loginUser = getLoginUser();
        return loginUser != null ? loginUser.getUsername() : null;
    }


}